<!--
 * @FileDescription: 搜索组件
 * @Author: Ronghao Zhu
 * @CreateTime: 2020/10/09 星期五
 * @LastEditors: Ronghao Zhu
 * @LastEditTime: 2020/10/09
-->

<template>
  <el-form v-if="isSearchShow" class="search-form-inline" :inline="true" :model="formInline" @submit.native.prevent>
    <!-- 选择单位 -->
    <el-form-item v-if="$store.state.userInfo.isMuilUnitUser">
      <el-select filterable placeholder="选择单位" v-model="orgId" @change="changeOrgId">
        <el-option v-for="item in orgList" :key="item.orgId" :label="item.orgName" :value="item.orgId"></el-option>
        <i class="iconfont icondanwei" slot="prefix"></i>
      </el-select>
    </el-form-item>
    <!-- 选择楼栋 -->
    <el-form-item v-if="!isUnityMap">
      <el-select filterable placeholder="选择楼栋" clearable v-model="buildId" @change="changeBuildId" @clear="handleClearBuild">
        <el-option v-for="item in buildList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        <i class="iconfont iconloudong" slot="prefix"></i>
      </el-select>
    </el-form-item>
    <!-- 选择楼层 -->
    <el-form-item v-if="!isUnityMap">
      <el-select filterable placeholder="选择楼层" clearable v-model="floorId" @change="changeFloorId">
        <el-option v-for="item in floorList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        <i class="iconfont iconlouceng" slot="prefix"></i>
      </el-select>
    </el-form-item>
    <!-- 模糊搜索输入框 -->
    <el-form-item v-if="!isUnityMap">
      <el-autocomplete
        ref="elautocomplete"
        v-model="queryContent"
        placeholder="搜索消防设施"
        clearable
        :trigger-on-focus="false"
        :fetch-suggestions="getRestaurants"
        @clear="clearQueryContent"
        @select="handleSelect"
      >
        <i slot="prefix" class="iconfont iconsousuoxiaofangsheshi"></i>
      </el-autocomplete>
    </el-form-item>
  </el-form>
</template>

<script>
import { getMarkers, getMenu } from '@/api/indoorMap'
import { initGisInfo } from '@/api/gis'
import TrafficVue from '../../Detail/Model/PlatformManage/PageModel/Traffic.vue'

let fengMap = null

export default {
  name: 'Search',
  components: {},
  props: {
    id: {
      default() {
        return false
      },
    },
    isUnityMap: {
      type: Boolean,
    },
  },
  data() {
    return {
      isSearchShow: this.$store.state.isSearchShow,
      queryContent: '',
      orgId: this.$store.state.currentOrgId, // 当前单位Id
      buildId: this.$store.state.currentBuildId || '', // 楼栋Id
      floorId: this.$store.state.currentFloorId || '', // 楼层Id
      isOver: false,
      buildList: [], // 楼栋list
      floorList: [], // 楼层list
      restaurants: [], // 模糊搜索结果
      deployInfo: [],
      formInline: {
        orgIds: this.$store.state.userInfo.organizationIds,
        types: '', // 标注类型
        typeGroup: 1, // 室内地图标注关联类型
        name: '',
        indoorMapId: this.id, // 室内地图id
        indoorId: '', // 室内地图楼层id，若室内地图有楼层则传，没有则不传
        queryType: 0,
        pageIndex: 0,
        pageSize: 10,
      },
    }
  },
  computed: {
    routeList() {
      return this.$store.state.routeList
    },
    orgList() {
      return this.$store.state.orgList
    },
  },
  watch: {
    id: {
      handler(val) {
        if (val) this.formInline.indoorMapId = val
      },
      deep: true,
    },
    /* 监听vuex中orgId值的变化 做相应跳转 */
    '$store.state.currentOrgId': {
      handler(newVal, oldVal) {
        this.lastOrgId = ''
        this.buildList = []
        this.buildId = ''
        this.lastBuildId = ''
        this.floorList = []
        this.floorId = ''
        if (newVal) {
          this.orgId = Number(newVal)
          this.formInline.orgIds = newVal
          if (!this.isUnityMap) this.getOutDoorBuildInfo(newVal)
        } else {
          this.orgId = ''
        }
      },
      deep: true,
    },
    /* 监听vuex中buildId的值 */
    '$store.state.currentBuildId': {
      handler(newVal, oldVal) {
        if (this.isUnityMap) return
        this.lastBuildId = ''
        this.floorId = ''
        this.floorList = []
        this.buildId = newVal
        if (newVal) {
          this.getFloorsByBuildId(newVal)
        }
      },
      deep: true,
    },
    /* 监听vuex中floorId的值 */
    '$store.state.currentFloorId': {
      handler(newVal, oldVal) {
        if (this.isUnityMap) return
        this.floorId = newVal
      },
      deep: true,
    },
    /* 监听搜索框的显示与隐藏 只在消防维保隐藏 */
    '$store.state.isSearchShow': {
      handler(newVal, oldVal) {
        this.isSearchShow = newVal
      },
      deep: true,
    },
    /* 监听模糊搜索框 */
    queryContent(newVal, oldVal) {
      if (this.isUnityMap) return
      if (!newVal) return
      if (!newVal && this.buildId) {
        // this.changeBuildId(this.buildId);
        return
      }
      if (!newVal && this.orgId && !this.buildId) {
        this.$Ctl.enterSingleHome({
          orgId: this.orgId,
        })
        return
      }
    },
    '$store.state.mapSceneTypeStamp'() {
      this.changeScenes(1)
    },
  },
  created() {
    this.lastOrgId = ''
    this.lastBuildId = ''
    // 单单位首页进来直接获取楼栋信息
    if (this.$store.state.userInfo.isMuilUnitUser === 0) {
      this.$store.commit('setCurrentOrgId', this.$store.state.userInfo.org.id)
      if (!this.isUnityMap) {
        this.$emit('changeMapType', 1)
        this.getOutDoorBuildInfo(this.$store.state.userInfo.org.id)
      }
    } else if (this.$store.state.currentOrgId) {
      this.getOutDoorBuildInfo(this.$store.state.currentOrgId)
    }
  },
  methods: {
    // 切换单位 获取当前单位下的楼栋信息
    changeOrgId(val) {
      this.buildList = [] // 每次切换单位的时候 都将楼栋置空
      this.floorList = [] // 每次切换单位的时候 都将楼层置空
      this.$store.commit('setCurrentOrgId', val)
      this.$store.commit('setCurrentBuildId', '')
      this.$store.commit('setCurrentFloorId', '')
      this.$emit('changeMapType', 1)
      if (!val) {
        this.queryContent = ''
        this.$Ctl.backHome()
      } else {
        // this.$emit("sendSearchOrgId", val);
        this.orgId = Number(val)
        var routes = JSON.parse(localStorage.getItem('ilinkBs_routeList'))
        var lastRoute = routes[routes.length - 1]
        let param = {
          orgId: Number(val),
          isRefresh: true,
          lastPageName: lastRoute.name,
        }
        this.$Ctl.enterSingleHome(param)
      }
    },
    // 判断是多单位首页还是单单位首页
    isHomeMuil() {
      let isMisMuilUnitUser = this.$store.state.userInfo.isMuilUnitUser //0:单单位用户;1:多单位用户
      let _OrgIds = localStorage.getItem('ilinkBs_orgIds')
      return isMisMuilUnitUser && _OrgIds.split(',').length > 1 ? true : false
    },
    // 获取室外楼栋数据
    getOutDoorBuildInfo(orgIds, callback) {
      if (!orgIds) return // 单位选择为空
      getMenu({
        orgIds,
        type: 3,
      }).then((res) => {
        if (res.status === 200) {
          this.buildList = res.data
          this.lastOrgId = orgIds
          callback && callback()
        }
      })
    },
    // 切换楼栋下拉框
    changeBuildId(buildId) {
      this.floorList = [] // 每次切换楼栋的时候 都将楼层置空
      this.$store.commit('setCurrentBuildId', buildId)
      this.$store.commit('setCurrentFloorId', '')
      if (!buildId) {
        this.queryContent = ''
        return
      }
      this.initBuildMap(buildId)
    },
    initBuildMap(buildId, callback) {
      // 获取该楼栋的地图信息渲染
      let param = {
        bizId: buildId,
        type: 2,
        idType: 2,
      }
      initGisInfo(param).then((res) => {
        if (res.data && res.data.gisInfo) {
          let gisInfo = res.data.gisInfo
          localStorage.setItem('ilinkBs_mapGisInfo', JSON.stringify(gisInfo))
          this.$emit('initFengMap', res.data.gisInfo, (gisInfo) => {
            this.$Ctl.refreshMapMarkerDataToFmap()
            callback && callback()
          })
        } else {
          this.$Ctl.message('暂无该地图信息', 'info')
        }
      })
    },
    handleClearBuild() {
      this.changeScenes(1)
    },
    getFloorsByBuildId(buildId, callback) {
      getMenu({
        orgIds: this.formInline.orgIds,
        type: 4,
        parentId: buildId,
      }).then((res) => {
        if (res.status === 200) {
          this.floorList = res.data
          this.floorList.reverse()
          this.lastBuildId = buildId
          callback && callback()
        }
      })
    },
    // 切换楼层
    changeFloorId(val) {
      this.$store.commit('setCurrentFloorId', val)
      this.queryContent = ''
      this.$emit('setFengMap')
      // 楼层置空时回到建筑物地图
      if (!val) {
        this.formInline.indoorId = ''
        this.changeScenes(3)
        return
      }
      for (var i = 0; i < this.floorList.length; i++) {
        if (this.floorList[i].id === val) {
          this.focusGroup(this.floorList[i].indoorId, this.floorList[i])
          this.formInline.indoorId = this.floorList[i].indoorId // 支持楼层查询消防设施
        }
      }
    },
    setFengMap(_fengMap) {
      this.fengMap = _fengMap
    },
    // 单多层切换（需要传楼层id）
    focusGroup(indoorId, floorItem) {
      let that = this
      this.$emit('setFengMap')
      let groupId = null
      if (indoorId == null) {
        groupId = 1
      } else {
        groupId = indoorId
      }
      that.fengMap.showSingerOrMultiGroup(false)
      setTimeout(() => {
        that.deployInfo.forEach((item) => {
          if (Number(item.id) === Number(groupId)) {
            // that.floorId = groupId * 1;
            that.fengMap.mapScaleLevel = Number(item.scaleLevel)
          }
        })
        that.fengMap.focusGroupID = Number(groupId)
        if (floorItem && floorItem.center) {
          let coord = JSON.parse(floorItem.center)
          this.fengMap.moveTo({
            x: coord.x,
            y: coord.y,
            groupId,
          })
          this.fengMap.scaleLevelTo({ level: floorItem.scaleLevel || 20 })
        }
      }, 500)
      that.$emit('showHiddenGroupMarker', Number(groupId))
    },
    // 获取模糊搜索结果
    getRestaurants(queryString, callback) {
      this.$refs.elautocomplete.activated =
        true || this.$refs.elautocomplete.handleFocus()
      this.restaurants = []
      if (!queryString) return
      this.formInline.name = queryString
      getMarkers(this.formInline).then((res) => {
        if (res.status === 200) {
          for (let i of res.data) {
            i.value = i.name //将想要展示的数据作为value
          }
          this.restaurants = res.data
          callback(this.restaurants)
        }
      })
    },
    // 清空搜索框 回到楼栋层面
    clearQueryContent() {
      // this.changeBuildId(this.$store.state.currentBuildId);
      // const that = this;
      // that.$emit("setFengMap");
      // this.fengMap.showSingerOrMultiGroup(true);
      // that.fengMap.moveToCenter(that.floorList.length / 2);
    },
    // 搜索结果定位
    handleSelect(item) {
      this.$emit('setFengMap')
      // this.fengMap.showSingerOrMultiGroup(true);
      // this.$store.commit("setCurrentFloorId", "");
      this.$emit('searchLocation', item)
    },
    // 选中楼栋和楼层
    mapDbClick(indoorMapId, deployInfo, indoorId) {
      let orgId = this.$store.state.currentOrgId
      // 判断当前单位和楼栋所属单位是否一致
      if (this.lastOrgId == orgId) {
        this.filterBuildByIndoorMapId(indoorMapId, deployInfo, indoorId)
      } else {
        this.getOutDoorBuildInfo(orgId, () => {
          this.filterBuildByIndoorMapId(indoorMapId, deployInfo, indoorId)
        })
      }
    },
    // 根据indoorMapId过滤楼栋
    filterBuildByIndoorMapId(indoorMapId, deployInfo, indoorId) {
      this.deployInfo = deployInfo || []
      // 临时方案，应该定位信息接口返回楼栋id(现在是根据indoorMapId过滤楼栋)
      let obj = this.buildList.filter((n) => {
        return n.indoorMapId == indoorMapId
      })[0]
      if (obj) {
        this.$store.commit('setCurrentBuildId', obj.id)
        this.outBuildClick(obj, indoorId)
      } else {
        // 室外
        this.changeScenes(1)
      }
    },
    // 根据indoorId筛选楼层
    setFloorId(indoorId) {
      var obj = this.floorList.filter((n) => {
        return n.indoorId == indoorId
      })[0]
      if (obj) {
        this.$store.commit('setCurrentFloorId', obj.id)
      }
    },
    // 选择了室内楼栋
    outBuildClick(obj, indoorId) {
      let that = this
      // 获取楼层indoorId 用于回显楼层
      if (indoorId) {
        this.formInline.indoorId = indoorId
        // 当前楼栋的楼层已加载完成
        if (this.lastBuildId == obj.id) {
          this.setFloorId(indoorId)
        } else {
          this.getFloorsByBuildId(obj.id, () => {
            this.setFloorId(indoorId)
          })
        }
      }
      //获取地图配置信息
      initGisInfo({
        bizId: obj.id,
        type: 2,
        idType: 2,
      }).then((res) => {
        const gisInfo = res.data.gisInfo
        if (res.data && gisInfo) {
          that.$emit('changeMapType', 0)
          localStorage.setItem('ilinkBs_mapGisInfo', JSON.stringify(gisInfo))
          that.$emit('initFengMap', gisInfo, (gisInfo) => {
            that.$Ctl.refreshMapMarkerDataToFmap(() => {
              setTimeout(() => {
                this.$emit('setFengMap')
                indoorId && this.focusGroup(indoorId)
              }, 500)
            })
          })
        } else {
          that.$Ctl.message('暂无该地图信息', 'info')
        }
      })
    },
    // 切换室内/外
    changeScenes(type) {
      let that = this
      if (type == 1) {
        that.$emit('changeMapType', 1)
        localStorage.setItem('ilinkBs_mapSceneType', 1)
        // 切换到室外
        let param = {
          bizId: this.$store.state.currentOrgId,
          type: 2,
          idType: 1,
        }
        localStorage.setItem('ilinkBs_inoutDoorType', 1)
        localStorage.setItem('ilinkBs_fmapIndoorId', '')
        initGisInfo(param).then((re) => {
          if (re.data && re.data.gisInfo) {
            let gisInfo = re.data.gisInfo
            localStorage.setItem('ilinkBs_mapGisInfo', JSON.stringify(gisInfo))
            that.$emit('initFengMap', re.data.gisInfo, (gisInfo) => {
              that.$Ctl.refreshMapMarkerDataToFmap()
            })
          }
        })
      } else if (type == 3) {
        // 室内多层
        that.$emit('setFengMap')
        localStorage.setItem('ilinkBs_fmapIndoorId', '')
        that.fengMap.showSingerOrMultiGroup(true)
        // TODO:这个方法有问题，接处警和隐患定位偏移
        // setTimeout(() => {
        //   that.fengMap.mapScaleLevel = 20;
        //   that.fengMap.moveToCenter(Math.ceil(that.floorList.length / 2));
        // }, 500);
        that.$emit('showHiddenGroupMarker', -1)
        //日常巡检时单多层切换需要重新画线
        if (this.$store.state.currentInspectId) {
          that.$Ctl.refreshMapMarkerDataToFmap()
        }
      } else {
        that.focusGroup()
      }
    },
  },
}
</script>

<style lang="scss">
.search-form-inline {
  height: 42px;
  width: unset;
  border: 1px solid rgba($color: #51a6fa, $alpha: 0.6);
  border-radius: 5px;
  box-shadow: 0 0 5px #51a6fa inset;
  background-color: rgba($color: #51a6fa, $alpha: 0.2);
  .el-form-item {
    margin-right: 0;
    &:nth-child(1),
    &:nth-child(2),
    &:nth-child(3) {
      border-right: 1px solid rgba($color: #51a6fa, $alpha: 0.3);
    }
    &:nth-last-child(1) {
      border-right: none;
    }
  }
  .el-input.el-input--suffix {
    width: 130px;
    .el-input__prefix {
      left: 8px;
      color: #51a6fa;
      vertical-align: top;
    }
  }
  .el-autocomplete {
    width: 145px;
    .el-input--prefix {
      width: 145px;
      .el-input__inner {
        width: 145px;
        padding: 0 15px 0 30px;
      }
    }
  }
  .el-input__inner {
    width: 130px;
    color: #51a6fa;
    font-size: 16px;
    background: transparent;
    vertical-align: middle;
    border: transparent;
    &::placeholder {
      font-size: 16px;
    }
  }
  .el-select .el-input__inner {
    border: none;
    font-size: 16px;
    width: 130px;
  }
}
</style>
